package com.sise.wangzhan;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.Random;

/**
 * @Classname MyRule
 * @Description TODO
 * @Date 2020/3/25 20:39
 * @Created by wangzhan
 */
public class MyRule implements IRule {

    ILoadBalancer Ib;

    //*注意：千万不能漏掉，不然在控制台中会显示没有初始化
    public MyRule() {
    }

    public MyRule(ILoadBalancer Ib) {
        this.Ib = Ib;
    }

    @Override
    public Server choose(Object o) {
        List<Server> servers = Ib.getAllServers();
//        return servers.get(0);
        Random random = new Random();
        final int number = random.nextInt(10);
        if (number < 7){
            return findServer(servers,8081);
        }
        return findServer(servers,8085);
    }

    private Server findServer(List<Server> allServers, int port) {
        for (Server server : allServers){
            if (server.getPort() == port){
                return server;
            }
        }
        System.out.println("NULL port="+port);
        return null;
    }

    @Override
    public void setLoadBalancer(ILoadBalancer Ib) {
        this.Ib = Ib;
    }

    @Override
    public ILoadBalancer getLoadBalancer() {
        return this.Ib;
    }
}
